package com.xyz.admin.modules.demo.controller;

import com.sc.base.admin.modules.comm.controller.AbstractController;
import com.xyz.admin.common.utils.Rest;
import com.xyz.admin.config.Globals;
import com.xyz.admin.modules.demo.task.AsyncTaskDemo;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.Future;


@Api(tags = "Demo")
@RestController
@RequestMapping(value = "/api", params = { "ver="+ Globals.version})
public class DemoController extends AbstractController {


    @Autowired
    private AsyncTaskDemo asyncTaskDemo;

    /**
     * 异步方法执行
     */
    @ApiOperation(value="demoAsyncDemo")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "ver", value = "接口版本号", required = true, dataType = "String", paramType = "query")
    })
    @ApiResponses({
            @ApiResponse(code=404,message="请求路径没有或页面跳转路径不对")
    })
    @RequestMapping(value = "/taskDemo",method = RequestMethod.POST)
    public Rest test(@RequestParam(value="name",required = false) String name)throws Exception{
        //同步执行，等等任务完成后返回
        long start = System.currentTimeMillis();
        Future<String> task1 = asyncTaskDemo.doTaskA("test");
        while(true) {
            if(task1.isDone()) {
                // 任务调用完成，退出循环等待
                String str = task1.get();
                logger.info("任务全部完成Controller层收到信息:{}",str);
                break;
            }
            Thread.sleep(1000);
        }

        long end = System.currentTimeMillis();

        logger.info("任务全部完成，总耗时：{}毫秒", (end - start) );

        //异步执行，立即返回 需要在Application 上加注解@EnableAsync
        //asyncTaskDemo.doTaskB("test");
        return Rest.ok(name);
    }

}
